<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2016/10/9
 * Time: 11:50
 */
namespace app\home\controller;
use app\common\controller\HomeBase;
use think\Request;
use think\Session;

class Inbox extends HomeBase{
    public function index () {
        $join = [
            ['userinfo u','l.from=u.uid','LEFT'],
        ];
        $field = [
            'l.*','u.username','u.face','u.face50','u.uid'
        ];
        $objData = db('Letter')->alias('l')->join($join)->field($field)->where(['l.uid'=>Session::get('uid')])->paginate(6);
        // 获取分页显示
        $page = $objData->render();
        //组合数据
        $data = [];
        foreach ($objData as $comment) {
            $data[] = [
                'id' => $comment['id'],
                'content' => $comment['content'],
                'time' => $comment['time'],
                'uid' => $comment['uid'],
                'username' => $comment['username'],
                'face' => $comment['face'],
                'face50' => $comment['face50'],
            ];
        }
        $result = [
            'data' => $data,
            'page' => $page,
            'total' => db('Letter')->where(['uid'=>Session::get('uid')])->count(),
        ];
        return $this->fetch('index',['result'=>$result]);
    }

    //处理发送私信
    public function send_letter() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $username = trim(input('post.username'));
            if (!$uid = db('userinfo')->where(['username'=>$username])->value('uid')) return ['status'=>0,'msg'=>'该收信人不存在.^_^'];
            if ($uid == Session::get('uid')) return ['status'=>0,'msg'=>'不能给自己发私信哦.^_^'];
            $data = [
                'from' => Session::get('uid'),
                'content' => trim(input('post.content')),
                'uid' => $uid,
                'time' => time()
            ];
            if (db('letter')->insert($data)) {
                return ['status'=>1,'msg'=>'发送成功.^_^'];
            } else {
                return ['status'=>0,'msg'=>'系统发送错误,稍后请重试...'];
            }
        }
    }

    //删除私信
    public function send_del() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $id = input('post.lid',0,'intval');
            if (!$id) return ['status'=>0,'msg'=>'参数错误,请重试...'];
            if (db('Letter')->where(['id'=>$id])->delete()) {
                return ['status'=>1];
            } else {
                return ['status'=>0,'msg'=>'系统错误,请重试...'];
            }
        }
    }
}